package user

import (
	"context"
	"errors"
)

type Service interface {
	CreateUser(ctx context.Context, name, email string) (*User, error)
	GetUser(ctx context.Context, id int) (*User, error)
	UpdateUser(ctx context.Context, id int, name, email string) error
	DeleteUser(ctx context.Context, id int) error
	ListUsers(ctx context.Context) ([]*User, error)
}

// 具体实现
type service struct {
	repo Repository
}

func NewService(repo Repository) Service {
	return &service{repo: repo}
}

func (s *service) CreateUser(ctx context.Context, name, email string) (*User, error) {
	if name == "" || email == "" {
		return nil, errors.New("name and email are required")
	}

	user := &User{
		Name:  name,
		Email: email,
	}

	if err := s.repo.CreateUser(ctx, user); err != nil {
		return nil, err
	}

	return user, nil
}

func (s *service) GetUser(ctx context.Context, id int) (*User, error) {
	return s.repo.GetUser(ctx, id)
}

func (s *service) UpdateUser(ctx context.Context, id int, name, email string) error {
	user, err := s.repo.GetUser(ctx, id)
	if err != nil {
		return err
	}

	if name != "" {
		user.Name = name
	}
	if email != "" {
		user.Email = email
	}

	return s.repo.UpdateUser(ctx, user)
}

func (s *service) DeleteUser(ctx context.Context, id int) error {
	return s.repo.DeleteUser(ctx, id)
}

func (s *service) ListUsers(ctx context.Context) ([]*User, error) {
	return s.repo.ListUsers(ctx)
}
